﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

#if UNITY_EDITOR
[ExecuteInEditMode]
#endif
[AddComponentMenu("UI/Behavior/PivotIndex")]
public class UIPivotIndex : MonoBehaviour
{
    public Vector2[] pivots;
    private RectTransform _rect;
    public RectTransform rect
    {
        get
        {
            if(_rect == null)_rect = this.GetComponent<RectTransform>();
            return _rect;
        }
    }
    
    private void Awake()
    {
        _rect = this.GetComponent<RectTransform>();
    }


    [SerializeField]
    private int _index;
    public int index
    {
        get
        {
            return _index;
        }
        set
        {
            if (value > pivots.Length - 1) value = pivots.Length - 1;
            if (value < 0) value = 0;
            UpdateFromIndex(value);
            _index = value;
        }
    }


#if UNITY_EDITOR
    private bool _dirty = false;
    private void OnValidate()
    {
        if (pivots == null || pivots.Length <= 0) return;
        if (_index > pivots.Length - 1) _index = pivots.Length - 1;
        if (_index < 0) _index = 0;
        _dirty = true;
    }

    private void Update()
    {
        if (_dirty)
        {
            _dirty = false;
            UpdateFromIndex(_index);
        }
    }

#endif

    public Vector2 GetPivot(int index)
    {
        index = Mathf.Clamp(index, 0, pivots.Length);
        return pivots[index];
    }

    private void UpdateFromIndex(int value)
    {
        rect.pivot = GetPivot(value);
    }

}
